package com.personal.jdbc.dialect;

import java.util.Locale;

import com.personal.jdbc.exception.JdbcException;

/**
 * SqlServer
 * @author qq
 *
 */
public class SqlServerDialect extends JdbcDialect
{
    public String makePagging(String sql, int start, int limit)
    {
        String processSql = sql.toLowerCase(Locale.ENGLISH);
        int index = processSql.indexOf("order by");
        if (index <= 0)
        {
            throw new JdbcException("采用SQL Server数据库的分页查询需传入order by信息");
        } else
        {
            String orderStr = null;
            String beforeSql = null;
            if (index > 0)
            {
                orderStr = sql.substring(index + 8);
                beforeSql = sql.substring(0, index);
            }

            StringBuilder builder = new StringBuilder("select * from ");
            builder.append("(select row_number() over (order by ");
            builder.append(orderStr).append(") as rownum, * from (").append(beforeSql).append(") tb1) tb2 where ")
                    .append(" tb2.rownum > ").append(start).append(" and tb2.rownum <= ").append(start + limit);
            return builder.toString();
        }
    }

    public String makeCount(String sql)
    {
        String temp = sql.toLowerCase(Locale.ENGLISH);
        if (temp.contains(" order "))
        {
            int index = temp.indexOf(" order ");
            sql = sql.substring(0, index);
        }
        return "select count(1) from (" + sql + ") tab_name";
    }
}